package dk.eclipse.android.helpers;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import org.apache.http.util.ByteArrayBuffer;

import android.os.Handler;

/**
 * @author Ronni
 *
 */
public class WebHelper {

	public static void loadURL(final String url, ByteArrayBuffer baf,
			Runnable runnable) throws MalformedURLException {
		loadURL(new URL(url), baf, runnable);
	}

	public static void loadURL(final URL url, final ByteArrayBuffer baf,
			final Runnable runnable) {
		final Handler handler = new Handler();

		Thread checkUpdate = new Thread() {

			public void run() {
				URL updateURL = url;
				URLConnection conn;
				try {
					conn = updateURL.openConnection();
					InputStream is = conn.getInputStream();
					BufferedInputStream bis = new BufferedInputStream(is);

					int current = 0;
					while ((current = bis.read()) != -1) {
						baf.append((byte) current);
					}
					
				} catch (IOException e) {
					e.printStackTrace();
				}

				handler.post(runnable);
			}
		};
		checkUpdate.start();
	}
}
